/**
 * Class CreditorContextModule.
 *
 * @author Maxime Ollagnier
 */
CreditorContextModule.inherits(Module);
function CreditorContextModule() {
    var that = this;

    this.creditor = undefined;
    this.contextTable = undefined;
    this.context = undefined;

    /** Context table */
    this.contextTable = this.getContextTable();

    /** Input Modules */
    this.inputName = new InputTextModule({
        'id' : 'inputName',
        'label' : I18n.get('name'),
        'placeholder' : I18n.get('name'),
        'mandatory' : true,
        'validationPattern' : ValidationPattern.VALID_DEFAULT,
        'validationMethod' : new ValidationMethod({
            'errorMessage' : I18n.get('context.name.exists'),
            'method' : function(value) {
                var unique = true;
                that.contextTable.objectMap.foreach(function(id, context) {
                    unique = unique && (that.context.id == context.id || context.name != value);
                });
                return unique;
            }
        }),
        'onKeyUp' : function() { that.setJQFormTitle(); },
        'onEnter' : function() { that.saveContext(); }
    });
    this.inputIdentifier = new InputTextModule({
        'id' : 'inputIdentifier',
        'label' : I18n.get('identifier'),
        'placeholder' : I18n.get('identifier'),
        'mandatory' : true,
        'validationPattern' : ValidationPattern.VALID_DEFAULT,
        'validationMethod' : new ValidationMethod({
            'errorMessage' : I18n.get('context.identifier.exists'),
            'method' : function(value) {
                var unique = true;
                that.contextTable.objectMap.foreach(function(id, context) {
                    unique = unique && (that.context.id == context.id || context.identifier != value);
                });
                return unique;
            }
        }),
        'onKeyUp' : function() { that.setJQFormTitle(); },
        'onEnter' : function() { that.saveContext(); }
    });
    this.inputEmails = new InputMultipleValueTextModule({
        'id' : 'inputEmails',
        'label' : I18n.get('email.addresses'),
        'placeholder' : I18n.get('email'),
        'validationPattern' : ValidationPattern.VALID_EMAIL,
        'onChange' : function() { that.setJQFormTitle(); }
    });
}

CreditorContextModule.neededRoles = ['VIEW_CONTEXT'];

CreditorContextModule.prototype.fillJQ = function(jQ) {
    var that = this;

    // List title
    jQ.append($('<h5>' + I18n.get('context.list') + '</h5>'));

    // New button
    if (UserManager.hasRoles(['WRITE_CONTEXT'])) {
        var buttonNew = $('<div class="btn new">' + I18n.get('new') + ' <i class="icon-plus icon"/></div>');
        buttonNew.click(function() { that.newContext(); });
        jQ.find('h5:first').append(buttonNew);
    }

    // Contexts list
    jQ.append(this.contextTable.buildJQ());

    // Context edition form
    this.jQForm = $('<div id="contextEditionForm"></div>').hide();
    jQ.append(this.jQForm);

    // Fills form with selected context
    if (Util.checkObject(this.contextTable.selectedObject)) {
        this.editContext(this.contextTable.selectedObject.id);
    }
};

CreditorContextModule.prototype.fillJQForm = function() {
    var that = this;

    // Form title
    this.setJQFormTitle();

    // Form
    var form = $('<div class="well"></div>');
    this.jQForm.append(form);

    var nameRow = $('<div class="row-fluid"></div>');
    form.append(nameRow);
    var columnLeft = $('<div class="span6"></div>');
    columnLeft.append(this.inputName.buildJQ());
    var columnRight = $('<div class="span6"></div>');
    columnRight.append(this.inputIdentifier.buildJQ());
    nameRow.append(columnLeft).append(columnRight);

    var emailsRow = $('<div class="row-fluid"></div>');
    var column = $('<div class="span12" style="min-height:0"></div>');
    column.append(this.inputEmails.buildJQ());
    form.append(emailsRow.append(column));

    if (UserManager.hasRoles(['WRITE_CONTEXT'])) {
        var buttonRow = $('<div class="btn-row"></div>');
        form.append(buttonRow);
        var buttonSave = $('<div class="btn save">' + I18n.get('save') + '</div>');
        buttonSave.click(function() { that.saveContext(); });
        buttonRow.append(buttonSave);
    }
};

CreditorContextModule.prototype.setJQFormTitle = function() {
    var jQFormTitle = this.jQForm.children('h5:first');
    if (!Util.checkJQueryNotEmpty(jQFormTitle)) {
        jQFormTitle = $('<h5></h5>');
        this.jQForm.prepend(jQFormTitle);
    }
    jQFormTitle.clear();
    if (!Util.check(this.context.id)) {
        jQFormTitle.text(I18n.get('context.new'));
    } else {
        jQFormTitle.text(I18n.get('context') + ' - ' + this.context.name + ' (' + this.context.identifier + ')');
    }
    if (this.isContextModified()) {
        jQFormTitle.addClass('modified');
        jQFormTitle.append(' *');
    } else {
        jQFormTitle.removeClass('modified');
    }
};

CreditorContextModule.prototype.isContextModified = function() {
    return this.inputName.modified || this.inputIdentifier.modified || this.inputEmails.modified;
};

CreditorContextModule.prototype.loadData = function(callback) {
    var that = this;

    // Resets the table object map
    this.contextTable.objectMap = new Map();

    // Sets the creditor
    this.creditor = this.parameters.referrer;
    if (!Util.checkObject(this.creditor)) {
        return;
    }

    // Fetches the contexts of the creditor from the server and sets the table
    AjaxManager.getJSON('getContexts', {
        referrerId : this.creditor.id
    }, function(result) {
        if (result.success) {
            $.each(result.contexts, function(id, context) {
                that.contextTable.objectMap.put(id, context);
            });
            if (Util.checkObject(that.contextTable.selectedObject)) {
                that.contextTable.selectedObject = that.contextTable.objectMap.get(that.contextTable.selectedObject.id);
            }
        }
        Util.getFunction(callback)();
    });
};

CreditorContextModule.prototype.setContext = function(context) {
    context = Util.getObject(context);
    if (this.context != context) {
        this.context = context;

        this.inputName.modified = false;
        this.inputIdentifier.modified = false;
        this.inputEmails.modified = false;

        this.inputName.setValue(this.context.name);
        this.inputIdentifier.setValue(this.context.identifier);
        this.inputEmails.setValue(this.context.emails);
    }
    this.validate();
};

CreditorContextModule.prototype.newContext = function() {
    this.contextTable.unselect();
    this.setContext();
    this.jQForm.clear();
    this.fillJQForm();
    this.jQForm.show();
};

CreditorContextModule.prototype.editContext = function(contextId) {
    this.jQForm.clear();
    if (!Util.check(contextId)) {
        this.jQForm.hide();
        return;
    }
    this.setContext(this.contextTable.objectMap.get(contextId));
    this.fillJQForm();
    this.jQForm.show();
};

CreditorContextModule.prototype.deleteContext = function(contextId) {
    var that = this;
    AjaxManager.getJSON('deleteContext', {
        'contextId' : contextId
    }, function(result) {
        if (result.success) {
            that.reload();
        }
    });
};

CreditorContextModule.prototype.setDefault = function(contextId) {
    var that = this;
    AjaxManager.getJSON('setDefaultContext', {
        contextId : contextId
    }, function(result) {
        if (result.success) {
            that.creditor.defaultContextId = contextId;
            that.buildJQ();
        }
    });
};

CreditorContextModule.prototype.saveContext = function() {
    if(!this.validate()) {
        return;
    }

    var context = {};
    context.id = this.context.id;
    context.name = this.inputName.value;
    context.identifier = this.inputIdentifier.value;
    context.emails = this.inputEmails.getValue();
    context.emails = Util.checkStringNotEmpty(context.emails) ? context.emails : undefined;
    context.creditorId = this.creditor.id;

    var that = this;
    AjaxManager.getJSON('saveContext', {
        'context' : JSON.stringify(context)
    }, function(result) {
        if (result.success) {
            that.contextTable.selectedObject = result.context;
            if (that.contextTable.objectMap.size == 0) {
                that.creditor.defaultContextId = result.context.id;
            }
            that.reload();
        }
    });
};
CreditorContextModule.prototype.getContextTable = function() {
    var that = this;

    // Context table
    var contextTable = new TableModule({
        'selectable' : true,
        'onSelect' : function(contextId) {
            that.editContext(contextId);
        }
    });
    contextTable.id = 'contextTable';

    // Name column
    contextTable.columnList.push(new Column('name', I18n.get('name'), '15%', true));

    // Identifier column
    contextTable.columnList.push(new Column('identifier', I18n.get('identifier'), '15%', true));

    // Emails column
    var emailsColumn = new Column('emails', I18n.get('email.addresses'), '60%', true);
    emailsColumn.getText = function(context) {
        return Util.checkString(context.emails) ? context.emails.replace(new RegExp(InputMultipleValueTextModule.SEP, 'g'), '; ') : '';
    };
    emailsColumn.getAlt = emailsColumn.getText;
    contextTable.columnList.push(emailsColumn);

    // Default checkboxes column
    var defaultColumn = new Column('default', I18n.get('default'), '6%');
    defaultColumn.clickable = false;
    defaultColumn.getAlt = undefined;
    defaultColumn.getText = function(context) {
        var jQCheckbox = $('<input type="checkbox" ' + (that.creditor.defaultContextId == context.id ? 'checked="checked"' : '') + (UserManager.hasRoles(['WRITE_CONTEXT']) ? '' : ' disabled="disabled"') + '></input>');
        jQCheckbox.change(function() {
            that.setDefault(context.id);
        });
        return jQCheckbox;
    };
    contextTable.columnList.push(defaultColumn);

    // Delete action column
    var deleteCol = new Column('delete', '', '4%', false, true);
    deleteCol.clickable = false;
    deleteCol.getText = function(context) {
        if (!UserManager.hasRoles(['WRITE_CONTEXT']) || that.creditor.defaultContextId == context.id) {
            return '';
        }
        return $('<i class="icon-remove icon" />').click(function() {
            that.deleteContext(context.id);
        });
    };
    contextTable.columnList.push(deleteCol);

    return contextTable;
};
